package validator

import (
	"context"
	"gorm.io/gorm"
	"jk-time/webook/pkg/migrator"
	"jk-time/webook/pkg/migrator/events"
)

type CanalIncrValidator[T migrator.Entity] struct {
	baseValidator
}

func NewCanalIncrValidator[T migrator.Entity](bv baseValidator) *CanalIncrValidator[T] {
	return &CanalIncrValidator[T]{baseValidator: bv}
}

// Validate 一次校验一条
// id 是被修改的数据的主键
func (v *CanalIncrValidator[T]) Validate(ctx context.Context, id int64) error {
	var base T
	err := v.base.WithContext(ctx).Where("id=?", id).First(&base).Error
	switch err {
	case gorm.ErrRecordNotFound:
		return nil
	case nil:
		var target T
		err = v.target.WithContext(ctx).Where("id=?", base.ID()).First(&target).Error
		switch err {
		case gorm.ErrRecordNotFound:
			v.notify(ctx, base.ID(), events.InconsistentEventTypeTargetMissing)
			return nil
		case nil:
			// 两边都找到了
			if !base.CompareTo(target) {
				v.notify(ctx, base.ID(), events.InconsistentEventTypeNotEqual)
			}
			return nil
		default:
			return err
		}
	default:
		return err
	}
}
